package com.crm.system.service.impl.contractManager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.dto.InsertClueCallable;
import com.crm.model.dto.InsertContractCallable;
import com.crm.model.entity.cluePoolManager.Clue;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.sys.ImportExport;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.vo.cluePoolManager.ClueImportVO;
import com.crm.model.vo.contractReviewManager.ContractImportVO;
import com.crm.model.vo.contractReviewManager.ContractImportVO2;
import com.crm.service.contactManager.ContactDbService;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.sys.ImportExportDbService;
import com.crm.service.sys.ImportFailureLogDbService;
import com.crm.service.sys.UserAccountDbService;
import com.crm.service.sys.UserInfoDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import com.crm.system.service.contractManager.ContractImportService;
import com.crm.system.service.sys.ImportExportService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.annotation.Contract;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author luojie
 * @date 2021/6/2 9:05
 */
@Service
public class ContractImportServiceImpl implements ContractImportService {

    @Autowired
    private CustomerDbService customerDbService;
    @Autowired
    private CustomerContractDbService customerContractDbService;
    @Autowired
    private ImportExportService importExportService;
    @Autowired
    private UserInfoDbService userInfoDbService;
    @Autowired
    private ImportFailureLogDbService importFailureLogDbService;
    @Autowired
    private ContactDbService contactDbService;
    @Autowired
    private SysCompanyDbService companyDbService;
    @Autowired
    private UserAccountDbService userAccountDbService;

    /***
     * @Description:导入合同
     * @Param: list 合同列表
     * @Author: luojie
     * @Date: 2021/6/2 15:01
     */
    @Override
    public JSONObject contractImport(List<ContractImportVO> list) {
        //返回的结果集
        JSONObject jsonObject = new JSONObject();

        int count = 100;                   //一个线程处理300条数据
        int listSize = list.size();        //数据集合大小
        int runSize = (listSize/count)+1;  //开启的线程数
        //int runSize = importExportService.calculateImportedThreads(listSize);
        List<ContractImportVO> newlist = null;       //存放每个线程的执行数据

        ExecutorService executor = Executors.newCachedThreadPool();
        //创建两个个计数器
        CountDownLatch begin = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(runSize);
        List<FutureTask<JSONObject>> taskList = new ArrayList<FutureTask<JSONObject>>();
        for (int i = 0; i < runSize ; i++) {
            //计算每个线程执行的数据
            if ((i + 1) == runSize) {
                int startIndex = (i * count);
                int endIndex = list.size();
                newlist = list.subList(startIndex, endIndex);
            } else {
                int startIndex = (i * count);
                int endIndex = (i + 1) * count;
                newlist = list.subList(startIndex, endIndex);
            }
            FutureTask<JSONObject> futureTask = new FutureTask(new InsertContractCallable(newlist, begin, end,customerDbService,customerContractDbService,userInfoDbService,
                                                                                          importFailureLogDbService,contactDbService,companyDbService));
            taskList.add(futureTask);
            executor.submit(futureTask);//submit返回一个Future，代表了即将要返回的结果
        }

        //导入数量
        int importNum = 0;
        //客户名称为空列表
        List<Integer> customerEmptyIdList = new ArrayList();
        //客户不存在列表
        List<Integer> customerNotExistIdList = new ArrayList();
        //合同编号重复列表
        List<Integer> repeatIdList = new ArrayList();
        //所有人不存在列表
        List<Integer> ownerEmptyIdList = new ArrayList();
        //失败行数
        List<Integer> importFailIdList = new ArrayList();
        //未生效行数
        List<Integer> notValidIdList = new ArrayList();

        for (int i = 0; i < taskList.size(); i++) {
            try {
                // FutureTask的get方法会自动阻塞,直到获取计算结果为止
                //导入数量
                importNum = importNum + taskList.get(i).get().getInteger("importNum");

                //客户名称为空列表
                JSONArray customerEmptyIdArray = taskList.get(i).get().getJSONArray("customerEmptyIdList");
                for (int j = 0; j < customerEmptyIdArray.size(); j++){
                    int customerEmpty = Integer.parseInt(customerEmptyIdArray.get(j).toString());
                    customerEmptyIdList.add(customerEmpty + i*100);
                }

                //客户不存在列表
                JSONArray customerNotExistIdArray = taskList.get(i).get().getJSONArray("customerNotExistIdList");
                for (int j = 0; j < customerNotExistIdArray.size(); j++){
                    int customerNotExist = Integer.parseInt(customerNotExistIdArray.get(j).toString());
                    customerNotExistIdList.add(customerNotExist + i*100);
                }

                //合同编号重复列表
                JSONArray repeatIdArray = taskList.get(i).get().getJSONArray("repeatIdList");
                for (int j = 0; j < repeatIdArray.size(); j++){
                    int repeat = Integer.parseInt(repeatIdArray.get(j).toString());
                    repeatIdList.add(repeat + i*100);
                }

                //所有人不存在
                JSONArray ownerEmptyArray = taskList.get(i).get().getJSONArray("ownerEmptyIdList");
                for (int j = 0; j < ownerEmptyArray.size(); j++){
                    int ownerEmpty = Integer.parseInt(ownerEmptyArray.get(j).toString());
                    ownerEmptyIdList.add(ownerEmpty + i*100);
                }

                //失败行数
                JSONArray importFailIdArray = taskList.get(i).get().getJSONArray("importFailIdList");
                for (int j = 0; j < importFailIdArray.size(); j++){
                    int importFail = Integer.parseInt(importFailIdArray.get(j).toString());
                    importFailIdList.add(importFail + i*100);
                }

                //未生效行数
                JSONArray notValidIdArray = taskList.get(i).get().getJSONArray("notValidIdList");
                for (int j = 0; j < notValidIdArray.size(); j++){
                    int notValid = Integer.parseInt(notValidIdArray.get(j).toString());
                    notValidIdList.add(notValid + i*100);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        // 关闭线程池
        executor.shutdown();

        jsonObject.put("importContractNum", importNum);
        jsonObject.put("customerEmptyIdList", customerEmptyIdList);
        jsonObject.put("customerNotExistIdList", customerNotExistIdList);
        jsonObject.put("repeatIdList", repeatIdList);
        jsonObject.put("ownerEmptyIdList", ownerEmptyIdList);
        jsonObject.put("importFailIdList", importFailIdList);
        jsonObject.put("notValidIdList", notValidIdList);

        //插入导入表
        if (importNum > 0) {
            importExportService.insertExportService(importNum,"1","1","4");
        }
        return jsonObject;
    }

    @Override
    public JSONObject contractImport2(List<ContractImportVO2> list) {
        JSONObject jsonObject = new JSONObject();
        List<Integer> k = new ArrayList<>();
        List<Integer> j = new ArrayList<>();
        List<Integer> m = new ArrayList<>();
        SimpleDateFormat dateTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        for (int i = 0; i < list.size(); i++) {
            ContractImportVO2 contractImportVO2 = list.get(i);
            CustomerContract contract = new CustomerContract();
            contract.setContractId(CommonUtils.getGUID());
            contract.setContractNumber("C" + String.valueOf(new Date().getTime()));
            contract.setContractStatus("2");
            contract.setContractType("2");
            contract.setCustomerId(contractImportVO2.getCustomerId());
            contract.setCustomerName(contractImportVO2.getCustomerName());
            if(!StringUtils.isBlank(contractImportVO2.getMembershipStartTm())){
                try {
                    contract.setContractStartDate(dateTime.parse(contractImportVO2.getMembershipStartTm()));
                    contract.setCreateTm(dateTime.parse(contractImportVO2.getMembershipStartTm()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            if(!StringUtils.isBlank(contractImportVO2.getMembershipExpirationTm())){
                try {
                    contract.setContractEndDate(dateTime.parse(contractImportVO2.getMembershipExpirationTm()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            Customer customer = customerDbService.selectCustomerById(contractImportVO2.getCustomerId());
            if(customer!=null){
                contract.setCustomerType(customer.getCustomerType());
            }

            contract.setWhetherCheck("1");
            //合同审核状态2-审核通过
            contract.setContractReviewStatus("2");
            //回款状态1-已回款
            contract.setPaymentStatus("1");

            //所属分公司
            SysCompany sysCompany = companyDbService.selectSysCompanyByName(contractImportVO2.getCompanyName());
            if(sysCompany!=null){
                contract.setAffiliationCompanyId(sysCompany.getCompanyId());
            }else {
                k.add(i+2);
                continue;
            }
            contract.setContractCategory(0);
            contract.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));

            if(StringUtils.isBlank(contractImportVO2.getCreatePeopleId())){
                j.add(i+2);
                continue;
            }
            //所有人
            UserAccount userAccount = userAccountDbService.selectUserAccountByCompanyIdAndUserName(sysCompany.getCompanyId(),contractImportVO2.getCreatePeopleId());
            if(userAccount!=null){
                contract.setCreatePeopleId(userAccount.getAccountId());
                contract.setUpdatePeopleId(userAccount.getAccountId());
            }else{
                j.add(i+2);
                continue;
            }

            contract.setUpdateTm(new Date());
            contract.setOldContract("1");
            contract.setImportError("0");
            m.add(i+2);
            customerContractDbService.insertCustomerContract(contract);
        }
        jsonObject.put("k",k);
        jsonObject.put("j",j);
        jsonObject.put("m",m);
        return jsonObject;
    }


}
